package com.itheima.jobs;

import com.itheima.common.RedisConst;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

public class ClearImageJob {

    @Autowired
    JedisPool jedisPool;

    /**
     * 定时任务：
     *   清理redis缓存中的图片信息
     *   和七牛云上的图片
     */
    @Test
    public void Job(){
        Jedis jedis = jedisPool.getResource();

        Set<String> imgs = jedis.smembers(RedisConst.SETMEAL_PIC_RESOURCES);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        String time = sdf.format(date);
        //昨天的日期字符串

        for (String img : imgs) {
            /*判断redis中的所有图片信息 前缀以time开头的 也就是昨天的图片 给全删掉*/
            if (img.startsWith(time)){
                //删除七牛云上的图片
                  delQiniu(img);
                //删除redis库当中的
                jedis.srem(RedisConst.SETMEAL_PIC_RESOURCES,img);
            }
        }
    }


    //删除七牛云的方法
    public void delQiniu(String imgName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        String key = imgName;
        Auth auth = Auth.create("zXi4HrIXtsG5bDibApeu4-d3_d2e5_T4O6sbOjfe", "4RhvxWxCCz1UN8B0r8onUpOg0TS8BT8FRUoZYB8-");
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete("javamodel-1", key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }


}
